<script lang="ts" setup>
import { ref } from 'vue'
import * as integralProductApi from '@/api/integralProduct'
import { message } from 'ant-design-vue'
import ImgView from './ImgView.vue'

let imgViewRef = ref()

let title = ref<string>('新增兑换商品')
const open = ref<boolean>(false)
const confirmLoading = ref<boolean>(false)

let theType = ref<string>('')
let info = ref<any>()
const showModal = (type: string, record: any = {}) => {
  theType.value = type
  if (theType.value == 'add') {
    title.value = '新增兑换商品'
  } else {
    title.value = '编辑兑换商品'
    info.value = record
    formState.value.title = record.title
    formState.value.desc = record.desc
    formState.value.extend = record.extend
    formState.value.price = record.price
    formState.value.sort = record.sort
    formState.value.type = record.status
    imgList.value = [record.img]
    fileList.value = imgList.value.map(url => ({
      uid: Date.now() + Math.floor(Math.random() * 1000), // 为每个文件生成一个唯一的
      name: '文件名.jpg',
      url: url,
      status: 'done', // 表示文件已经上传完成
      type: 'image/*',
    }))
  }
  open.value = true
}

const cancel = () => {
  formRef.value.resetFields()
  imgList.value = []
  fileList.value = []
  open.value = false
  emit('refresh')
}

const add = () => {
  // console.log('imgList=', imgList.value)
  formRef.value.validate().then(async () => {
    confirmLoading.value = true
    let params = {
      title: formState.value.title,
      desc: formState.value.desc,
      extend: formState.value.extend,
      price: formState.value.price,
      status: formState.value.type,
      img: imgList.value[0],
      // img: 'https://liangpiao-ticket-img.oss-cn-beijing.aliyuncs.com/replyAnswerImg/9bfa7bda202c4673b5554d23f6e6178b.png',
      sort: formState.value.sort,
    }

    if (theType.value == 'add') {
      try {
        let { state, message: msg } = await integralProductApi.addPointProduct(params)
        if (state === 200) {
          message.success('添加成功')
          cancel()
        } else {
          message.error(msg)
        }
      } catch (error) {
        message.error('网络请求连接失败~')
      }
    } else if (theType.value == 'edit') {
      try {
        // @ts-ignore
        params.id = info.value.id
        let { state, message: msg } = await integralProductApi.editPointProduct(params)
        if (state === 200) {
          message.success('添加成功')
          cancel()
        } else {
          message.error(msg)
        }
      } catch (error) {
        message.error('网络请求连接失败~')
      }
    }

    confirmLoading.value = false
  })
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

const labelCol: any = {
  style: { width: '100px', textAlign: 'center' },
}
const formRef = ref()
interface FormState {
  title: string
  desc: string
  extend: string
  price: number
  type: number
  sort: number
}
const formState = ref<FormState>({
  title: '',
  desc: '',
  extend: '',
  price: 0,
  type: 1,
  sort: 0,
})

import type { SelectProps } from 'ant-design-vue'
const typeList = ref<SelectProps['options']>([
  {
    label: '上架',
    value: 1,
  },
  {
    label: '下架',
    value: 2,
  },
])

import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
}

// 商品图片
const imgList = ref<Array<string>>([])
interface FileItem {
  uid: string
  name?: string
  status?: string
}
let fileList = ref<FileItem[]>([])
const handleBeforeUpload = (file: any, fileList: any) => {
  return true
}
const customRequest = (option: any) => {
  const { onSuccess, onError, file, action, data = {} } = option
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', '1')
  fetch(action, {
    headers: {
      'User-Token': localStorage.getItem('token') as any,
    },
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(result => {
      onSuccess(result, file)
      if (result && result.data != null) {
        imgList.value.push(result.data)
      } else {
        message.error('图片太大，上传失败了!')
        fileList.value.pop()
      }
    })
    .catch(error => {
      message.error('图片太大，上传失败了')
      onError(error)
    })
}

// 预览图片
const handlePreview = async (file: any) => {
  // console.log('file=', file)
  if (theType.value == 'add') {
    if (file && file.response) {
      imgViewRef.value.setVisible(true, file.response.data)
    } else {
      message.error('预览失败！')
    }
  } else if (theType.value == 'edit') {
    imgViewRef.value.setVisible(true, file.url)
  } else {
    message.error('预览失败！')
  }
}

// 删除图片
const handleRemove = (file: any) => {
  // console.log('file=', file)
  if (theType.value == 'add') {
    if (file.status != 'error') {
      imgList.value = imgList.value.filter(item => item != file.response.data)
    }
  } else {
    if (file.status != 'error') {
      imgList.value = imgList.value.filter(item => item != file.url)
    }
  }
}

interface FileInfo {
  file: FileItem
  fileList: FileItem[]
}
const handleChange = ({ fileList: newFileList }: FileInfo) => {
  fileList.value = newFileList.map((item: any) => {
    if (item.response && item.response.result == false) {
      return {
        uid: '-5',
        name: 'image.png',
        status: 'error',
      }
    } else {
      return item
    }
  })
}
</script>

<template>
  <a-modal
    v-model:open="open"
    :title="title"
    :confirm-loading="confirmLoading"
    @ok="add"
    @cancel="cancel"
    centered
  >
    <div style="margin: 30px 36px 0 0">
      <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol">
        <a-form-item label="商品标题" name="title">
          <a-input v-model:value="formState.title"></a-input>
        </a-form-item>

        <a-form-item label="商品描述" name="desc">
          <a-textarea
            v-model:value="formState.desc"
            style="max-height: 120px"
            :maxlength="1000"
          ></a-textarea>
        </a-form-item>

        <a-form-item label="商品标识" name="extend">
          <a-input v-model:value="formState.extend"></a-input>
        </a-form-item>

        <a-form-item has-feedback name="images" label="商品图片">
          <a-upload
            :multiple="true"
            list-type="picture-card"
            action="http://crm.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
            :show-upload-list="{ showRemoveIcon: true }"
            :beforeUpload="handleBeforeUpload"
            :customRequest="customRequest"
            @preview="handlePreview"
            @remove="handleRemove"
            @change="handleChange"
            :file-list="fileList"
            :max-count="1"
          >
            <upload-outlined></upload-outlined>
            上传图片
          </a-upload>
        </a-form-item>

        <a-form-item has-feedback label="积分" name="price">
          <a-input-number v-model:value="formState.price" style="width: 100%"></a-input-number>
        </a-form-item>

        <a-form-item has-feedback label="排序" name="sort">
          <template #help>排序越大，越靠前</template>
          <a-input-number v-model:value="formState.sort" style="width: 100%"></a-input-number>
        </a-form-item>

        <a-form-item label="商品状态" name="type">
          <a-select v-model:value="formState.type" placeholder="商品状态">
            <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>

  <ImgView ref="imgViewRef"></ImgView>
</template>
